package leetcode.editor.cn;

import java.util.List;

//Java：两两交换链表中的节点
public class SwapNodesInPairs {
    public static void main(String[] args) {
        Solution solution = new SwapNodesInPairs().new Solution();
        // TO TEST
    }
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
    /**
     * 两两交换主要是模拟交互的过程。
     * 问题一：为什么最后cur = firstNode;而不是cur = secondNode;
     * 答：因为最后firstNode的位置是以前secondNode的位置，下次要处理的是cur后面的节点，也就是firstNode后面的节点
     * <p>
     * 问题二：while循环中为什么是 cur.next != null && cur.next.next != null？
     * 因为从极限的角度来看，cur指的是开始的虚拟节点，需要交换位置的是从虚拟节点往后的两个节点
     */
    class Solution {
        public ListNode swapPairs(ListNode head) {
            ListNode pre = new ListNode(-1, head);
            ListNode cur = pre;
            ListNode firstNode;
            ListNode secondNode;
            while (cur.next != null && cur.next.next != null) {
                firstNode = cur.next;
                secondNode = firstNode.next;
                ListNode temp = secondNode.next;
                cur.next = secondNode;
                secondNode.next = firstNode;
                firstNode.next = temp;
                cur = firstNode;
            }
            return pre.next;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}